/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef UGAME_CRYPTO_BIGNUMBER_H_
#define UGAME_CRYPTO_BIGNUMBER_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <cstdint>
#include <boost/scoped_array.hpp>

struct bignum_st;

namespace UGame {
namespace Crypto {

	class BigNumber
	{
	public:
		BigNumber(void);
		BigNumber(const BigNumber& _Bn);
		BigNumber(std::uint32_t);
		~BigNumber(void);
	
	public:
		void SetUInt32(std::uint32_t);
		void SetUInt64(std::uint64_t);
		void SetBinary(const std::uint8_t*, int);
		void SetHexStr(const char*);
		void SetRand(int);
	
		static void Free(void*);
	
		BigNumber operator=(const BigNumber&);
	
		BigNumber operator+=(const BigNumber&);
		BigNumber operator+(const BigNumber& x)
		{
			BigNumber t(*this);
			return t += x;
		}
	
		BigNumber operator-=(const BigNumber&);
		BigNumber operator-(const BigNumber& x)
		{
			BigNumber t(*this);
			return t -= x;
		}
	
		BigNumber operator*=(const BigNumber&);
		BigNumber operator*(const BigNumber& x)
		{
			BigNumber t(*this);
			return t *= x;
		}
	
		BigNumber operator/=(const BigNumber&);
		BigNumber operator/(const BigNumber& x)
		{
			BigNumber t(*this);
			return t /= x;
		}
	
		BigNumber operator%=(const BigNumber&);
		BigNumber operator%(const BigNumber& x)
		{
			BigNumber t(*this);
			return t %= x;
		}
	
		bool IsZero(void) const;
		BigNumber ModExp(const BigNumber&, const BigNumber&);
		BigNumber Exp(const BigNumber&);
		int GetNumBytes(void);
		inline struct bignum_st* bn(void) { return _bn; }
		uint32_t AsUInt32(void);
		std::uint8_t* AsByteArray(int _MinSize = 0);
		const char* AsHexStr(void);
		const char* AsDecStr(void);
	
	private:
		struct bignum_st* _bn;
		boost::scoped_array<std::uint8_t> _array;
	};

}}

#endif /* UGAME_CRYPTO_BIGNUMBER_H_ */
